package com.kangjia.model.m3.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.general.dao.GeneralDao;
import com.kangjia.http.HttpParam;
import com.kangjia.http.HttpRequest;
import com.kangjia.http.HttpResponse;
import com.kangjia.jasckson.DataMapper;
import com.kangjia.model.m3.entity.KangjiaKpi;
import com.kangjia.util.JsonNodeUtil;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 康加基础数据接口实现类
 * 
 * @author sunshulin
 *
 */
@Service
@Slf4j
public class BaseDataApiImpl {

	@Value("${kangjia.token.url}")
	private String url;
	@Autowired
	private GeneralDao generalDao;
	@Autowired
	protected JedisPool jedisPool;
	@Autowired
	protected HttpRequest httpRequest;
	@Value("${kangjia.secret}")
	private String secret;

	/**
	 * 获取康加基础数据,指标数据集
	 * @throws IOException 
	 * @throws JsonProcessingException 
	 */
	public void getBaseData() throws JsonProcessingException, IOException {
		String token = getKangjiaToken();
		List<HttpParam> params = new ArrayList<>();
		params.add(new HttpParam("version", "1.0"));
		params.add(new HttpParam("tradeType", "02"));
		params.add(new HttpParam("frontUrl", ""));
		params.add(new HttpParam("token", token));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		params.add(new HttpParam("reqTime", sdf.format(new Date())));
		params.add(new HttpParam("encoding", "utf-8"));
		params.add(new HttpParam("sign", getSign(params)));
		HttpResponse response = httpRequest.form(url + "getBaseData", params);
		JsonNode data = handlerResponse(response, "data");
		if (data != null) {
			Iterator<JsonNode> iterator = data.iterator();
			List<KangjiaKpi> list = new ArrayList<>();
			while (iterator.hasNext()) {
				JsonNode node = iterator.next();
				KangjiaKpi kangjiaKpi = create(node);
				generalDao.saveOrUpdate(kangjiaKpi);
				list.add(kangjiaKpi);
			}
			saveTemplate(list);
		} else {
			log.error("请求康加接口getBaseData出现异常,查看具体日志信息.");
		}
	}

	private KangjiaKpi create(JsonNode node) {
		KangjiaKpi kangjiaKpi = new KangjiaKpi();
		kangjiaKpi.setGuideContent(JsonNodeUtil.string(node, "guideContent"));
		kangjiaKpi.setImprovementProgram(JsonNodeUtil.string(node, "improvementProgram"));
		kangjiaKpi.setInspectExplain(JsonNodeUtil.string(node, "inspectExplain"));
		kangjiaKpi.setInspectLevel(JsonNodeUtil.integer(node, "inspectLevel"));
		kangjiaKpi.setInspectName(JsonNodeUtil.string(node, "inspectName"));
		kangjiaKpi.setParentId(JsonNodeUtil.integer(node, "parentId"));
		kangjiaKpi.setSorts(JsonNodeUtil.integer(node, "sort"));
		kangjiaKpi.setSuggestContent(JsonNodeUtil.string(node, "suggestContent"));
		kangjiaKpi.setTargetId(JsonNodeUtil.integer(node, "targetId"));
		kangjiaKpi.setType(JsonNodeUtil.integer(node, "type"));
		kangjiaKpi.setUpdateTime(JsonNodeUtil.string(node, "updateTime"));
		kangjiaKpi.setSuggestContent(JsonNodeUtil.string(node, "suggestContent"));
		return kangjiaKpi;
	}

	private void saveTemplate(List<KangjiaKpi> list) throws JsonProcessingException {
		Jedis jedis = jedisPool.getResource();
		for (KangjiaKpi kangjiaKpi : list) {
			String json = DataMapper.getInstance().writeValueAsString(kangjiaKpi);
			jedis.hset("kangjia.kpi.data", String.valueOf(kangjiaKpi.getTargetId()), json);
		}
		jedis.close();
	}
	
	/**
	 * http 响应结果处理方法
	 * 
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws JsonProcessingException 
	 */
	public JsonNode handlerResponse(HttpResponse response, String field) throws JsonProcessingException, IOException {
		log.info("响应码={}, 返回结果={}", response.getRpc(), response.getResponse());
		if (response.getRpc() == 200) {
			String rtnStr = response.getResponse();
			JsonNode jsonNode = DataMapper.getInstance().readTree(rtnStr);
			JsonNode rep = jsonNode.get("repCode");
			if (rep.asInt() == 200) {
				return jsonNode.get(field);
			}
		}
		return null;
	}
	
	/**
	 * 获取康加token
	 * 
	 * @return
	 */
	protected String getKangjiaToken() {
		Jedis jedis = jedisPool.getResource();
		String token = jedis.get("kangjia.token");
		jedis.close();
		return token;
	}
	
	/**
	 * 获取sign
	 * 
	 * @param params
	 * @return
	 */
	protected String getSign(List<HttpParam> params) {
		StringBuilder str = new StringBuilder();
		params.sort(new Comparator<HttpParam>() {
			public int compare(HttpParam o1, HttpParam o2) {
				String s1 = o1.getParam();
				String s2 = o2.getParam();
				return s1.compareTo(s2);
			}
		});
		for (HttpParam param : params) {
			str.append("&" + param.string());
		}
		String s = str.replace(0, 1, "").toString();
		log.info("参数 sign={}", s);
		HiiposmUtil util = new HiiposmUtil();
		return util.MD5Sign(s, secret);
	}
}
